package cn.favebook.db;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.favebook.Global;
import cn.favebook.bean.Weibo;

public class WeiboDao {
	
	public static void add(QueryRunner runner, Weibo weibo) throws SQLException {
		final String sql = "insert into weibo(content,publishDate,userId,userName) "
				+ "values(?,?,?,?)";
		runner.execute(sql, weibo.getContent(), weibo.getPublishDate(), weibo.getUserID(), weibo.getUserName());
	}
	
	public static void del(QueryRunner runner, int id) throws SQLException {
		final String sql = "delete from weibo where id = ?";
		runner.execute(sql, id);
	}
	
	public static long count(QueryRunner runner) throws SQLException {
		final String sql = "select count(id) from weibo";
		return runner.query(sql, new ScalarHandler<Long>());
	}
	
	public static long perCount(QueryRunner runner, int id) throws SQLException {
		final String sql = "select count(id) from weibo where userId=?";
		return runner.query(sql, new ScalarHandler<Long>(), id);
	}
	
//	public static void update(QueryRunner runner, Weibo newArticle) {
//		
//	}
	
	public static List<Weibo> find(QueryRunner runner, int pageNum) throws SQLException {
		final String sql = "select id, content, publishDate, userId, userName from weibo "
				+ "order by publishDate desc limit ? offset ?";
		return runner.query(sql, new BeanListHandler<>(Weibo.class), 
				Global.PAGE_SIZE, pageNum * Global.PAGE_SIZE);
	}
	
	public static int findOne(QueryRunner runner, int id) throws SQLException {
		final String sql = "select userId from weibo where id=?";
		return runner.execute(sql, id);
	}
}
